package com.example.whowwroteit.apis;

import android.os.AsyncTask;
import android.widget.TextView;

import com.example.whowwroteit.R;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.ref.WeakReference;

public class FetchBook extends AsyncTask<String, Void, String> {
  private WeakReference<TextView> mTitleText;
  private WeakReference<TextView> mAuthorText;

  public FetchBook(TextView title, TextView author) {
    this.mTitleText = new WeakReference<>(title);
    this.mAuthorText = new WeakReference<>(author);
  }

  @Override
  protected void onPostExecute(String s) {
    super.onPostExecute(s);
    try {
      JSONObject jsonObject = new JSONObject(s);
      JSONArray itemsArray = jsonObject.getJSONArray("items");
      String title = null;
      String author = null;
      int i = 0;
      while (i < itemsArray.length() && title == null && author == null) {
        JSONObject item = itemsArray.getJSONObject(i);
        JSONObject volumeInfo = item.getJSONObject("volumeInfo");
        title = volumeInfo.getString("title");
        author = volumeInfo.getString("authors");
        i++;
      }
      if (title != null && author != null) {
        mTitleText.get().setText(title);
        mAuthorText.get().setText(author);
      } else {
        mTitleText.get().setText(R.string.no_results);
        mAuthorText.get().setText("");
      }
    } catch (JSONException e) {
      mTitleText.get().setText(R.string.no_results);
      mAuthorText.get().setText("");
      e.printStackTrace();
    }
  }

  @Override
  protected String doInBackground(String... strings) {
    return NetworkUtils.getBookInfo(strings[0]);
  }
}
